<?php
/**
 *
 * @author yupoxiong<i@yupoxiong.com>
 */

declare (strict_types=1);

namespace app\api\controller;

use app\common\validate\UserValidate;
use think\facade\Config;
use think\Request;
use think\response\Json;
use app\api\service\AuthService;
use app\api\exception\ApiServiceException;

class AuthController
{
    /**
     * @param Request $request
     * @param UserValidate $validate
     * @param AuthService $service
     * @return Json
     */
    public function login(Request $request, UserValidate $validate,AuthService $service): Json
    {
        $param = $request->param();

        $check = $validate->scene('api_login')->check($param);
        if (!$check) {
            return api_error($validate->getError());
        }

        try {

            $username = $param['username'];
            $password = $param['password'];
            $result = $service->usernameLogin($username, $password);

            return api_success($result);
        } catch (ApiServiceException $e) {
            return api_error('登录失败，参考信息：'.$e->getMessage());
        }
    }

    //小程序登录
    public function sign(Request $request,AuthService $service) :Json
    {
        try {
            $param = $request->param();
            if (!isset($param['code']) || empty($param['code'])) {
                throw new ApiServiceException('参数不足：code');
            }
            $applet_config = Config::get('wechat.applet');
            $code = $param['code'];//小程序传来的code值
            $url = 'https://api.weixin.qq.com/sns/jscode2session?appid=' . $applet_config['appid'] . '&secret=' . $applet_config['app_secret'] . '&js_code=' . $code . '&grant_type=authorization_code';

            $info = file_get_contents($url);//发送HTTPs请求并获取返回的数据，推荐使用curl
            //$info = '{"openid":"fdfdsfdsfasf"}';
            $json = json_decode($info);//对json数据解码
            $arr = get_object_vars($json);
            $openid = $arr['openid'];

            $result = $service->appletLogin($openid);

            return api_success($result);
        } catch (ApiServiceException $e) {
            return api_error('小程序登录失败，参考信息：'.$e->getMessage());
        }
    }

}